<script setup lang="tsx">
import { ref, useAttrs } from 'vue'
import { ElButton, ElMessage, useFormDisabled } from 'element-plus'
import { useDesign } from '@sat/shared-hooks'
import { CodeMirror } from '../../CodeMirror'
import type { CodeMirror as CodeMirrorSFC } from '../../CodeMirror'

defineProps<{
  disabled?: boolean
}>()
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('json-editor')

const attrs = useAttrs()

const inputDisabled = useFormDisabled()

const modelValue = defineModel<string>('modelValue')

const satCodeMirrorRef = ref<InstanceType<typeof CodeMirrorSFC>>()

function formatJson() {
  try {
    if (!modelValue.value)
      return
    modelValue.value = JSON.stringify(JSON.parse(modelValue.value), null, 2)
  }
  catch (error: any) {
    ElMessage.warning(error.message)
  }
}

defineExpose({
  getCodeMirrorRef: () => satCodeMirrorRef,
  formatJson,
})
</script>

<template>
  <div class="w-full" :class="[prefixCls]">
    <ElButton
      v-if="!disabled"
      type="primary"
      size="small"
      class="mb-10px"
      @click="formatJson"
    >
      格式化
    </ElButton>

    <CodeMirror
      ref="satCodeMirrorRef"
      v-model="modelValue"
      lang="json"
      :disabled="inputDisabled"
      v-bind="attrs"
      @blur="formatJson"
    />
  </div>
</template>

<style lang="less" scoped></style>
